# 设置车辆的自动驾驶参数（速度，距离等）
import carla
import argparse


def get_vehicle_from_client(world, vehicle_name='*vehicle*'):
    """从client中找到车辆"""
    actors = world.get_actors()
    vehicle_actor_list = actors.filter(vehicle_name)
    vehicle_actor = vehicle_actor_list[0]
    return vehicle_actor


def get_orin_setting(world):
    settings = world.get_settings()
    return settings


def set_world_synchronous_mode(world):
    settings = world.get_settings()
    if not settings.synchronous_mode:
        settings.synchronous_mode = True
        # settings.fixed_delta_seconds = 0.05
    world.apply_settings(settings)


def set_world_asynchronous_mode(world):
    settings = world.get_settings()
    settings.asynchronous_mode = False
    # settings.fixed_delta_seconds = 0.05
    world.apply_settings(settings)


def main():
    argparser = argparse.ArgumentParser(description=__doc__)
    argparser.add_argument(
        '--host',
        metavar='H',
        default='127.0.0.1',
        help='IP of the host server (default: 127.0.0.1)',
    )
    argparser.add_argument(
        '-p',
        '--port',
        metavar='P',
        default=2000,
        type=int,
        help='TCP port to listen to (default: 2000)',
    )
    argparser.add_argument(
        '-s',
        '--speed',
        metavar='FACTOR',
        default=0.0,
        type=float,
        help='rate at which the weather changes (default: 1.0)',
    )
    argparser.add_argument(
        '--tm_port',
        metavar='P',
        default=8000,
        type=int,
        help='Port to communicate with TM (default: 9000)')
    args = argparser.parse_args()
    client = carla.Client(args.host, args.port)
    client.set_timeout(10.0)
    world = client.get_world()
    Traffic_manager = client.get_trafficmanager(port=args.tm_port)
    orin_setting = get_orin_setting(world)
    Traffic_manager.set_hybrid_physics_mode(True)
    while True:
        try:
            vehicle_actor = get_vehicle_from_client(world, vehicle_name='vehicle.audi.tt')
            # 获取交通流管理器
            set_world_synchronous_mode(world)
            Traffic_manager.set_synchronous_mode(True)
            tm_port = Traffic_manager.get_port()
            # 获取车辆actor
            # 设置车辆为自动驾驶
            vehicle_actor.set_autopilot(True, tm_port)
            # 解锁权限
            # danger_car = vehicle_actor
            Traffic_manager.auto_lane_change(vehicle_actor, True)
            Traffic_manager.ignore_lights_percentage(vehicle_actor, 100)
            # Traffic_manager.distance_to_leading_vehicle(vehicle_actor, 5)
            Traffic_manager.vehicle_percentage_speed_difference(
                vehicle_actor, -args.speed
            )  # 可以超速20%
        except KeyboardInterrupt:
            # 退出时将世界设置为原来的模式
            world.apply_settings(orin_setting)
            Traffic_manager.vehicle_percentage_speed_difference(
                vehicle_actor, 0
            )  # 降速20%
            vehicle_actor.set_autopilot(False, tm_port)

            print("exit")
            break
        except IndexError:
            pass


if __name__ == '__main__':
    main()
